//
//  RHLoginViewController.swift
//  IMF
//
//  Created by 黄瑞东 on 2018/9/12.
//  Copyright © 2018年 imf. All rights reserved.
//

import UIKit
import TangramKit
import SVProgressHUD

class RHLoginViewController: RHRootLayoutController {

    var userNameTextField: UITextField?
    var userPasswordTextField: UITextField?
    var sendMsgButton: UIButton?
    var loginButton: UIButton?
    var smsID: String?
    var timer: Timer?
    var timeCount = 60
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = NSLocalizedString("LoginText", comment: "")
        createContentLayout()
        
        self.userNameTextField!.delegate = self
        self.userPasswordTextField!.delegate = self
        self.userNameTextField!.addTarget(self, action: #selector(textFieldValueChanged(send:)), for: .editingChanged)
        self.userPasswordTextField!.addTarget(self, action: #selector(textFieldValueChanged(send:)), for: .editingChanged)
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录帮助", style: UIBarButtonItemStyle.plain, target: self, action: #selector(loginHelpClick))
    }
    
    @objc func loginHelpClick() {
        let alertController = UIAlertController(title: "",
                                                message: "请联系公司运维", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "好的", style: .default, handler: {
            action in
            print("点击了确定")
        })
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    func createContentLayout() {
        let contentLayout = TGLinearLayout(.vert)
        contentLayout.backgroundColor = RHAppSkinColor.sharedInstance.viewBackgroundColor
        contentLayout.tg_top.equal(10)
        contentLayout.tg_left.equal(0)
        contentLayout.tg_right.equal(0)
        contentLayout.tg_height.equal(.wrap)
        self.rootLayout.addSubview(contentLayout)
        
        let loginIconImageView = UIImageView(image:UIImage(named:"logo"))
        loginIconImageView.tg_top.equal(UIScreen.main.bounds.size.height * 0.05)
        loginIconImageView.tg_centerX.equal(contentLayout.tg_centerX)
        loginIconImageView.tg_size(width: 100, height: 100)
        contentLayout.addSubview(loginIconImageView)
        
        let textFieldContentLayout = TGLinearLayout(.vert)
        textFieldContentLayout.backgroundColor = .white
        textFieldContentLayout.tg_top.equal(loginIconImageView.tg_bottom).offset(UIScreen.main.bounds.size.height * 0.1)
        textFieldContentLayout.tg_left.equal(15.0)
        textFieldContentLayout.tg_right.equal(15.0)
        textFieldContentLayout.tg_height.equal(.wrap)
        contentLayout.addSubview(textFieldContentLayout)
        
        userNameTextField = UITextField.xz_textFieldWithFontSize(size: 16.0, placeholderText: NSLocalizedString("UserPlaceholder", comment: ""), text: nil, isShowClearButton: true)
        userNameTextField?.tag = 10000
        userNameTextField?.tg_top.equal(textFieldContentLayout.tg_top)
        userNameTextField?.tg_left.equal(15.0)
        userNameTextField?.tg_right.equal(0)
        userNameTextField?.tg_height.equal(44)
        textFieldContentLayout.addSubview(userNameTextField!)
        userNameTextField?.keyboardType = .phonePad
        let lineView = UIView()
        lineView.backgroundColor = RHAppSkinColor.sharedInstance.separatorColor
        lineView.tg_top.equal(userNameTextField!.tg_bottom)
        lineView.tg_left.equal(0)
        lineView.tg_right.equal(0)
        lineView.tg_height.equal(1)
        textFieldContentLayout.addSubview(lineView)
        
        let passwordLinearLayout = TGLinearLayout(.horz)
        passwordLinearLayout.tg_top.equal(0)
        passwordLinearLayout.tg_left.equal(0)
        passwordLinearLayout.tg_right.equal(0)
        passwordLinearLayout.tg_height.equal(.wrap)
        textFieldContentLayout.addSubview(passwordLinearLayout)
        
        userPasswordTextField = UITextField.xz_textFieldWithFontSize(size: 16.0, placeholderText: NSLocalizedString("PasswordPlaceholder", comment: ""), text: nil, isShowClearButton: true)
        userPasswordTextField?.tag = 10001
        userPasswordTextField?.tg_top.equal(passwordLinearLayout.tg_top)
        userPasswordTextField?.tg_left.equal(15.0)
        userPasswordTextField?.tg_right.equal(10)
        userPasswordTextField?.tg_width.equal(UIScreen.main.bounds.size.width/2)
        userPasswordTextField?.tg_height.equal(44)
        passwordLinearLayout.addSubview(userPasswordTextField!)
        userPasswordTextField?.keyboardType = .phonePad

        sendMsgButton = UIButton.xz_buttonWithFontSize(size: 16, title: NSLocalizedString("GetSMSCode", comment: ""), textColor:UIColor.blue, backgroundColor: nil)
        sendMsgButton?.addTarget(self, action: #selector(sendMsgButtonClick), for: .touchUpInside)
        sendMsgButton?.tg_top.equal(userPasswordTextField!.tg_top)
        sendMsgButton?.tg_left.equal(userPasswordTextField!.tg_right).offset(15.0)
        sendMsgButton?.tg_right.equal(30.0)
        sendMsgButton?.tg_width.equal(120)
        sendMsgButton?.tg_height.equal(44)
        passwordLinearLayout.addSubview(sendMsgButton!)

        let loginButton = UIButton.xz_commonButtonWithTitle(title: NSLocalizedString("LoginText", comment: ""), isEnabled: false)
        loginButton.addTarget(self, action: #selector(loginButtonClick), for: .touchUpInside)
        loginButton.tg_top.equal(userPasswordTextField!.tg_bottom).offset(UIScreen.main.bounds.size.height * 0.05)
        loginButton.tg_left.equal(15.0)
        loginButton.tg_right.equal(15.0)
        loginButton.tg_height.equal(44)
        contentLayout.addSubview(loginButton)
        self.loginButton = loginButton;
    }
    
    @objc private func textFieldValueChanged(send: UITextField) {
        self.loginButton!.isEnabled = self.userNameTextField!.text!.count == 11 && self.userPasswordTextField!.text!.count == 6;
    }
    
    @objc func loginButtonClick() {
        if self.smsID == nil {
            SVProgressHUD.showInfo(withStatus: NSLocalizedString("GetSMSCodeError", comment: ""))
            return;
        }
        SVProgressHUD.show()
        RHAPIManager.sharedInstance.doLogin(userName: (userNameTextField?.text)!, msgCode: (userPasswordTextField?.text)!, msgId: self.smsID!, result: { [weak self] (msg, data) in
            guard let weakSelf = self else { return }
            SVProgressHUD.dismiss()
            weakSelf.dismiss(animated: true, completion: nil)
            let model = data as! RHLoginResponseModel
            RHAppUserProfile.sharedInstance.save(token: model.data)
        }) { (code, message) in
            SVProgressHUD.dismiss()
            SVProgressHUD.showInfo(withStatus: message)
        }
    }
    
    @objc func sendMsgButtonClick() {
        if !RHValidateString.sharedInstance.isPhoneNumber(phone: (userNameTextField?.text)!){
            SVProgressHUD.showInfo(withStatus: NSLocalizedString("PhoneError", comment: ""))
            return;
        }
        SVProgressHUD.show()
        RHAPIManager.sharedInstance.doGetSMSCode(phone: (userNameTextField?.text)!, result: { [weak self] (msg, data) in
            guard let weakSelf = self else { return }
            SVProgressHUD.dismiss()
            let model = data as! RHSMSCodeResponseModel
            weakSelf.smsID = model.data
            weakSelf.timeCount = 60
            weakSelf.sendMsgButton?.isMultipleTouchEnabled = false
            weakSelf.timer = Timer.scheduledTimer(timeInterval: 1,
                                                  target:weakSelf,selector:#selector(self?.triggerTimer),
                                         userInfo:nil,repeats:true)
        }) { (code, message) in
            SVProgressHUD.dismiss()
            SVProgressHUD.showInfo(withStatus: message)
        }
    }
    
    @objc func triggerTimer(){
        timeCount -= 1
        self.sendMsgButton?.setTitle("\(timeCount)" + NSLocalizedString("SecondsText", comment: ""), for: .normal)
        self.sendMsgButton?.setTitleColor(RHAppSkinColor.sharedInstance.secondaryTextColor, for: .normal)
        if timeCount == 0 {
            self.timer?.invalidate()
            self.sendMsgButton?.isMultipleTouchEnabled = true
            self.sendMsgButton?.setTitleColor(UIColor.blue, for: .normal)
            self.sendMsgButton?.setTitle(NSLocalizedString("GetSMSCode", comment: ""), for: .normal)
        }
    }
}

extension RHLoginViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let text = textField.text else {
            return true
        }
        
        let scanner = Scanner(string: string)
        let numbers = NSCharacterSet(charactersIn: "0123456789")
        if !scanner.scanCharacters(from: numbers as CharacterSet, into: nil) && string.count != 0 {
            return false
        }

        let textLength = text.count + string.count - range.length
        
        if textField.tag == 10000 {
            return textLength <= 11
        }else {
            return textLength <= 6
        }
    }
    func sha1() -> String{
        let data = Data()
        var digest = [UInt8](repeating:0,count:Int(CC_SHA1_DIGEST_LENGTH))
        
        let dataBytes = data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> UnsafePointer<UInt8> in
            return bytes
        }
        let dataLength = CC_LONG(data.count)
        
        CC_SHA1(dataBytes, dataLength, &digest)
        
        let output = NSMutableString(capacity: Int(CC_SHA1_DIGEST_LENGTH))
        for byte in digest{
            output.appendFormat("%02x", byte)
        }
        return output as String
    }

}
